#include "AnalysisWidget.h"
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QDateTime>
#include <QLabel>
#include <QMessageBox>
#include <QFormLayout>
#include <QGroupBox>
#include <QPdfWriter>
#include <QPrintPreviewDialog>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QFileDialog>
#include <QStandardPaths>
#include <QSpinBox>
#include <QDoubleSpinBox>
#include <QPainter>
#include <QtMath>
#include <QPixmap>
#include <QDesktopServices>
#include <QUrl>
#include "DatabaseManager.h"

// 构造函数实现
AnalysisWidget::AnalysisWidget(QWidget* parent)
    : QWidget(parent)
{
    // 初始化界面
    initUI();

    // 初始化信号连接
    initConnections();
}

// 获取正确的数据库连接
QSqlDatabase AnalysisWidget::getDatabase() {
    // 首先尝试获取主连接
    QSqlDatabase db = QSqlDatabase::database("MainConnection", false);

    if (!db.isValid()) {
        // 如果主连接不存在，尝试默认连接
        db = QSqlDatabase::database();

        if (!db.isValid()) {
            // 如果都不存在，通过DatabaseManager获取
            DatabaseManager* dbManager = DatabaseManager::getInstance();
            if (dbManager) {
                // 创建一个临时连接用于报告生成
                db = QSqlDatabase::addDatabase("QSQLITE", "ReportConnection");
                db.setDatabaseName("physio_data.sqlite");
                if (!db.open()) {
                    qWarning() << "无法打开报告生成专用数据库连接:" << db.lastError().text();
                }
            }
        }
    }

    return db;
}

// 添加槽函数实现
void AnalysisWidget::onStartTraining() {
    // 检查是否已选择模型和数据集
    if (m_selectedModel.isEmpty()) {
        QMessageBox::warning(this, "警告", "请先选择或创建模型");
        return;
    }

    if (m_eegDataset.isEmpty() && m_ecgDataset.isEmpty() && m_gsrDataset.isEmpty()) {
        QMessageBox::warning(this, "警告", "请至少选择一个数据集");
        return;
    }

    // 禁用控件，防止用户在训练过程中修改参数
    setControlsEnabled(false);

    // 准备训练命令和参数
    QStringList arguments;
    arguments << "--mode" << "train";
    arguments << "--model" << m_selectedModel;

    // 添加数据集参数
    if (!m_eegDataset.isEmpty()) {
        arguments << "--eeg_data" << m_eegDataset;
    }
    if (!m_ecgDataset.isEmpty()) {
        arguments << "--ecg_data" << m_ecgDataset;
    }
    if (!m_gsrDataset.isEmpty()) {
        arguments << "--gsr_data" << m_gsrDataset;
    }

    // 添加算法特定参数
    if (m_analysisMethod == "FFT") {
        arguments << "--method" << "fft";
        arguments << "--window_size" << QString::number(m_fftWindowSize);
        arguments << "--window_type" << m_fftWindowType;
        arguments << "--overlap" << QString::number(m_fftOverlap);
    } else if (m_analysisMethod == "Wavelet") {
        arguments << "--method" << "wavelet";
        arguments << "--wavelet_type" << m_waveletType;
        arguments << "--level" << QString::number(m_waveletLevel);
    } else if (m_analysisMethod == "ML") {
        arguments << "--method" << "ml";
        arguments << "--algorithm" << m_mlAlgorithm;
        arguments << "--feature_selection" << m_mlFeatureSelection;
        arguments << "--cv" << QString::number(m_mlCrossValidation);
    } else if (m_analysisMethod == "DL") {
        arguments << "--method" << "dl";
        arguments << "--architecture" << m_dlArchitecture;
        arguments << "--epochs" << QString::number(m_dlEpochs);
        arguments << "--batch_size" << QString::number(m_dlBatchSize);
        arguments << "--learning_rate" << QString::number(m_dlLearningRate, 'f', 6);
    }

    // 添加输出参数
    if (m_saveResults) {
        arguments << "--save_results";
        arguments << "--output_format" << m_outputFormat;
    }

    // 清空输出文本框
    m_outputEdit->clear();
    m_outputEdit->append("开始训练模型: " + m_selectedModel);
    m_outputEdit->append("使用方法: " + m_analysisMethod);
    m_outputEdit->append("命令行参数: " + arguments.join(" "));
    m_outputEdit->append("----------------------------");

    // 发射训练开始信号
    emit trainingStarted("开始训练模型: " + m_selectedModel);

    // 启动训练进程
    if (m_process == nullptr) {
        m_process = new QProcess(this);
        connect(m_process, &QProcess::readyReadStandardOutput, this, &AnalysisWidget::onProcessOutput);
        connect(m_process, static_cast<void(QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished),
                this, &AnalysisWidget::onProcessFinished);
    }

    // 启动Python脚本或其他训练程序
    m_process->start("python", QStringList() << "train_model.py" << arguments);

    if (!m_process->waitForStarted()) {
        m_outputEdit->append("错误: 无法启动训练进程");
        setControlsEnabled(true);
    }
}

void AnalysisWidget::onStartInference() {
    // 检查是否已选择模型
    if (m_selectedModel.isEmpty()) {
        QMessageBox::warning(this, "警告", "请先选择模型");
        return;
    }

    // 禁用控件，防止用户在推理过程中修改参数
    setControlsEnabled(false);

    // 准备推理命令和参数
    QStringList arguments;
    arguments << "--mode" << "inference";
    arguments << "--model" << m_selectedModel;

    // 添加数据源参数 - 推理可能使用实时数据或选定的测试数据集
    if (!m_eegDataset.isEmpty()) {
        arguments << "--eeg_data" << m_eegDataset;
    }
    if (!m_ecgDataset.isEmpty()) {
        arguments << "--ecg_data" << m_ecgDataset;
    }
    if (!m_gsrDataset.isEmpty()) {
        arguments << "--gsr_data" << m_gsrDataset;
    }

    // 添加算法特定参数
    if (m_analysisMethod == "FFT") {
        arguments << "--method" << "fft";
        arguments << "--window_size" << QString::number(m_fftWindowSize);
        arguments << "--window_type" << m_fftWindowType;
        arguments << "--overlap" << QString::number(m_fftOverlap);
    } else if (m_analysisMethod == "Wavelet") {
        arguments << "--method" << "wavelet";
        arguments << "--wavelet_type" << m_waveletType;
        arguments << "--level" << QString::number(m_waveletLevel);
    }

    // 添加输出参数
    if (m_saveResults) {
        arguments << "--save_results";
        arguments << "--output_format" << m_outputFormat;
    }

    if (m_generateReportBool) {
        arguments << "--generate_report";
    }

    // 清空输出文本框
    m_outputEdit->clear();
    m_outputEdit->append("开始推理: " + m_selectedModel);
    m_outputEdit->append("使用方法: " + m_analysisMethod);
    m_outputEdit->append("命令行参数: " + arguments.join(" "));
    m_outputEdit->append("----------------------------");

    // 发射推理开始信号
    emit inferenceStarted("开始推理: " + m_selectedModel);

    // 启动推理进程
    if (m_process == nullptr) {
        m_process = new QProcess(this);
        connect(m_process, &QProcess::readyReadStandardOutput, this, &AnalysisWidget::onProcessOutput);
        connect(m_process, static_cast<void(QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished),
                this, &AnalysisWidget::onProcessFinished);
    }

    // 启动Python脚本或其他推理程序
    m_process->start("python", QStringList() << "inference.py" << arguments);

    if (!m_process->waitForStarted()) {
        m_outputEdit->append("错误: 无法启动推理进程");
        setControlsEnabled(true);
    }
}

void AnalysisWidget::onProcessOutput()
{
    // 处理进程输出
    if (m_process) {
        // 读取标准输出
        QByteArray output = m_process->readAllStandardOutput();
        if (!output.isEmpty()) {
            m_outputEdit->append(QString::fromUtf8(output));
        }

        // 读取标准错误
        QByteArray error = m_process->readAllStandardError();
        if (!error.isEmpty()) {
            m_outputEdit->append(QString("<span style=\"color:red\">%1</span>").arg(QString::fromUtf8(error)));
        }
    }
}

void AnalysisWidget::onProcessFinished(int exitCode, QProcess::ExitStatus exitStatus)
{
    // 处理进程结束事件
    QString statusMessage;

    if (exitStatus == QProcess::NormalExit) {
        if (exitCode == 0) {
            statusMessage = "处理成功完成";
        } else {
            statusMessage = QString("处理完成，但返回错误代码 %1").arg(exitCode);
        }
    } else {
        statusMessage = "处理异常终止";
    }

    m_outputEdit->append(QString("[%1] %2")
                             .arg(QDateTime::currentDateTime().toString("HH:mm:ss"))
                             .arg(statusMessage));

    // 启用界面控件
    setControlsEnabled(true);
}

void AnalysisWidget::onSelectModel()
{
    // 打开文件对话框选择模型
    QString modelPath = QFileDialog::getOpenFileName(this,
                                                     tr("选择模型文件"),
                                                     QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation),
                                                     tr("模型文件 (*.h5 *.pb *.onnx *.pt *.pth)"));

    if (!modelPath.isEmpty()) {
        m_selectedModel = modelPath;
        m_modelEdit->setText(QFileInfo(modelPath).fileName());
    }
}

void AnalysisWidget::onSelectEEGDataset(int index)
{
    // 根据下拉框索引设置EEG数据集
    if (index >= 0 && m_eegDatasetCombo) {
        m_eegDataset = m_eegDatasetCombo->itemData(index).toString();

        // 验证模型与数据集匹配
        validateModelDatasetMatch(index);
    }
}

void AnalysisWidget::onSelectECGDataset(int index)
{
    // 根据下拉框索引设置ECG数据集
    if (index >= 0 && m_ecgDatasetCombo) {
        m_ecgDataset = m_ecgDatasetCombo->itemData(index).toString();
    }
}

void AnalysisWidget::onSelectGSRDataset(int index)
{
    // 根据下拉框索引设置GSR数据集
    if (index >= 0 && m_gsrDatasetCombo) {
        m_gsrDataset = m_gsrDatasetCombo->itemData(index).toString();
    }
}

void AnalysisWidget::validateModelDatasetMatch(int datasetIndex)
{
    // 验证所选模型与数据集是否匹配
    if (datasetIndex >= 0 && !m_selectedModel.isEmpty()) {
        QFileInfo modelInfo(m_selectedModel);
        QString modelName = modelInfo.baseName();

        // 获取数据集名称
        QString datasetName;
        if (m_eegDatasetCombo) {
            datasetName = m_eegDatasetCombo->itemText(datasetIndex);
        }

        // 简单验证：检查模型名称是否包含数据集名称的一部分
        // 实际应用中可能需要更复杂的验证逻辑
        if (!datasetName.isEmpty() && !modelName.contains(datasetName, Qt::CaseInsensitive)) {
            QMessageBox::warning(this, tr("模型匹配警告"),
                                 tr("所选模型 (%1) 可能与数据集 (%2) 不匹配。\n"
                                    "请确保使用与数据集兼容的模型。")
                                     .arg(modelName)
                                     .arg(datasetName));
        }
    }
}

void AnalysisWidget::setAnalysisMethod(const QString& method)
{
    m_analysisMethod = method;

    // 根据分析方法更新UI
    updateUIForAnalysisMethod();
}

void AnalysisWidget::setFFTParameters(int windowSize, const QString& windowType, int overlap)
{
    m_fftWindowSize = windowSize;
    m_fftWindowType = windowType;
    m_fftOverlap = overlap;
}

void AnalysisWidget::setWaveletParameters(const QString& waveletType, int level)
{
    m_waveletType = waveletType;
    m_waveletLevel = level;
}

void AnalysisWidget::setMLParameters(const QString& algorithm, const QString& featureSelection, int crossValidation)
{
    m_mlAlgorithm = algorithm;
    m_mlFeatureSelection = featureSelection;
    m_mlCrossValidation = crossValidation;
}

void AnalysisWidget::setDLParameters(const QString& architecture, int epochs, int batchSize, double learningRate)
{
    m_dlArchitecture = architecture;
    m_dlEpochs = epochs;
    m_dlBatchSize = batchSize;
    m_dlLearningRate = learningRate;
}

void AnalysisWidget::setSaveResults(bool save)
{
    m_saveResults = save;
}

void AnalysisWidget::setOutputFormat(const QString& format)
{
    m_outputFormat = format;
}

void AnalysisWidget::setGenerateReport(bool generate)
{
    m_generateReportBool = generate;
}

void AnalysisWidget::generateReport() {
    // 获取正确的数据库连接
    QSqlDatabase db = getDatabase();

    if (!db.isValid()) {
        QMessageBox::critical(this, "数据库错误",
                              "无法获取数据库连接。\n\n可能的解决方案：\n"
                              "1. 检查数据库文件是否存在\n"
                              "2. 重新启动应用程序\n"
                              "3. 联系技术支持");
        return;
    }

    if (!db.isOpen()) {
        // 尝试打开数据库连接
        if (!db.open()) {
            QMessageBox::critical(this, "数据库错误",
                                  "数据库无法打开。\n\n错误信息：" + db.lastError().text() +
                                      "\n\n可能的解决方案：\n"
                                      "1. 检查数据库文件权限\n"
                                      "2. 确保数据库文件未被其他程序占用\n"
                                      "3. 重新启动应用程序");
            return;
        }
    }

    // 从数据库读取被试信息和测试数据
    QMap<QString, QString> subjectInfo = getSubjectInfoFromDB();
    QMap<QString, double> testScores = getTestScoresFromDB();

    // 检查数据有效性（现在会显示详细错误信息）
    if (!validateReportData(subjectInfo, testScores)) {
        // validateReportData 已经显示了详细错误信息，这里不需要再显示通用错误
        return;
    }

    // 继续原有的报告生成逻辑...
    // 创建保存文件对话框
    QString defaultPath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);
    QString fileName = QFileDialog::getSaveFileName(this, tr("保存报告"),
                                                    defaultPath + "/脑健康分析报告.pdf",
                                                    tr("PDF文件 (*.pdf)"));
    if (fileName.isEmpty()) {
        return;
    }

    // 确保文件名以.pdf结尾
    if (!fileName.endsWith(".pdf", Qt::CaseInsensitive)) {
        fileName += ".pdf";
    }

    // 创建PDF写入器
    QPdfWriter pdfWriter(fileName);
    pdfWriter.setPageSize(QPageSize(QPageSize::A4));
    pdfWriter.setResolution(300);

    // 创建绘图器
    QPainter painter;

    if (!painter.begin(&pdfWriter)) {
        QMessageBox::critical(this, "绘图失败", "无法创建 PDF 绘图器，请检查文件路径或权限。");
        return;
    }


    painter.setRenderHint(QPainter::Antialiasing, true);
    painter.setRenderHint(QPainter::TextAntialiasing, true);
    painter.setRenderHint(QPainter::SmoothPixmapTransform, true);

    // 页面尺寸
    QRectF pageRect = pdfWriter.pageLayout().paintRectPixels(pdfWriter.resolution());
    int pageWidth = pageRect.width();
    int pageHeight = pageRect.height();
    int margin = 50;

    // 绘制第一页
    int yPos = margin;

    // 绘制背景模板（根据性别选择）
    drawBackgroundTemplate(painter, subjectInfo["gender"]);

    // 绘制基本信息
    drawBasicInfo(painter, yPos, subjectInfo);

    // 计算当前测试分数和结果
    int recordNum = getCurrentRecordNum();
    double currentScore = getCurrentTestScore(testScores, recordNum);
    int resultType = calculateResultType(currentScore);

    // 绘制当前测试结果
    drawCurrentTestResult(painter, yPos, currentScore, resultType);

    // 绘制扇形图（5次测试历史）
    drawSectorChart(painter, yPos, testScores, recordNum);

    // 绘制波形数据
    drawWaveformsFromDB(painter, yPos);

    // 开始第二页
    pdfWriter.newPage();
    yPos = margin;

    // 绘制第二页背景（根据结果类型）
    drawResultBackground(painter, resultType);

    // 结束绘图
    painter.end();

    // 显示成功消息并自动打开PDF
    QMessageBox::information(this, tr("报告生成成功"),
                             tr("脑健康分析报告已成功生成，保存在:\n") + fileName);

    // 自动打开PDF文件
    QDesktopServices::openUrl(QUrl::fromLocalFile(fileName));

    m_outputEdit->append(QString("[%1] 报告生成成功: %2")
                             .arg(QDateTime::currentDateTime().toString("HH:mm:ss"))
                             .arg(fileName));
}


// 从数据库读取被试信息
QMap<QString, QString> AnalysisWidget::getSubjectInfoFromDB() {
    QMap<QString, QString> info;

    // 获取正确的数据库连接
    QSqlDatabase db = getDatabase();
    if (!db.isValid() || !db.isOpen()) {
        qWarning() << "getSubjectInfoFromDB: 数据库连接失败";
        return info;
    }

    // 获取当前被试ID
    int currentSubjectId = getCurrentSubjectId();
    //int currentSubjectId = 1;

    if (currentSubjectId <= 0) {
        qWarning() << "getSubjectInfoFromDB: 当前被试ID无效:" << currentSubjectId;
        return info;
    }

    // 查询被试基本信息
    QSqlQuery query(db);
    query.prepare("SELECT name, gender, age, timestamp FROM subjects WHERE id = ?");
    query.addBindValue(currentSubjectId);

    if (!query.exec()) {
        qWarning() << "getSubjectInfoFromDB: 查询被试信息失败:" << query.lastError().text();
        return info;
    }

    if (query.next()) {
        info["number"] = QString::number(currentSubjectId);
        info["name"] = query.value(0).toString();
        info["gender"] = query.value(1).toString();
        info["age"] = query.value(2).toString();

        // 格式化时间戳
        qint64 timestamp = query.value(3).toLongLong();
        QDateTime dateTime = QDateTime::fromSecsSinceEpoch(timestamp);
        info["time"] = dateTime.toString("yyyy.MM.dd");

        qDebug() << "getSubjectInfoFromDB: 成功获取被试信息, ID:" << currentSubjectId
                 << "姓名:" << info["name"] << "性别:" << info["gender"];
    } else {
        qWarning() << "getSubjectInfoFromDB: 未找到ID为" << currentSubjectId << "的被试记录";
    }

    return info;
}

// 从数据库读取测试分数
QMap<QString, double> AnalysisWidget::getTestScoresFromDB() {
    QMap<QString, double> scores;

    // 初始化默认分数（-1表示未测试）
    scores["first_score"] = -1.0;
    scores["second_score"] = -1.0;
    scores["third_score"] = -1.0;
    scores["fourth_score"] = -1.0;
    scores["fifth_score"] = -1.0;

    // 获取正确的数据库连接
    QSqlDatabase db = getDatabase();
    if (!db.isValid() || !db.isOpen()) {
        qWarning() << "getTestScoresFromDB: 数据库连接失败，使用默认分数";
        return scores; // 返回默认分数而不是空的map
    }

    int currentSubjectId = getCurrentSubjectId();
    //int currentSubjectId = 1;

    if (currentSubjectId <= 0) {
        qWarning() << "getTestScoresFromDB: 当前被试ID无效，使用默认分数";
        return scores; // 返回默认分数而不是空的map
    }

    // 查询测试分数
    QSqlQuery query(db);
    query.prepare("SELECT test_number, score FROM test_scores WHERE subject_id = ? ORDER BY test_number");
    query.addBindValue(currentSubjectId);

    if (!query.exec()) {
        qWarning() << "getTestScoresFromDB: 查询测试分数失败:" << query.lastError().text();

        // 尝试从其他可能的表中获取分数
        query.prepare("SELECT item_name, value FROM analysis_results WHERE subject_id = ? ORDER BY timestamp DESC");
        query.addBindValue(currentSubjectId);

        if (query.exec() && query.next()) {
            // 如果找到分析结果，使用第一个结果作为当前分数
            double score = query.value(1).toDouble();
            scores["first_score"] = score;
            qDebug() << "getTestScoresFromDB: 从analysis_results表获取到分数:" << score;
        } else {
            qDebug() << "getTestScoresFromDB: 未找到任何测试分数，使用默认值";
        }

        return scores; // 返回默认分数或从analysis_results获取的分数
    }

    int foundScores = 0;
    while (query.next()) {
        int testNumber = query.value(0).toInt();
        double score = query.value(1).toDouble();
        foundScores++;

        switch (testNumber) {
        case 1: scores["first_score"] = score; break;
        case 2: scores["second_score"] = score; break;
        case 3: scores["third_score"] = score; break;
        case 4: scores["fourth_score"] = score; break;
        case 5: scores["fifth_score"] = score; break;
        }
    }

    if (foundScores == 0) {
        qDebug() << "getTestScoresFromDB: 未找到任何测试分数记录，使用默认值";
    } else {
        qDebug() << "getTestScoresFromDB: 成功获取" << foundScores << "个测试分数";
    }

    return scores;
}

// 验证报告数据
bool AnalysisWidget::validateReportData(const QMap<QString, QString>& subjectInfo,
                                        const QMap<QString, double>& testScores) {
    QStringList errorMessages;

    // 检查数据库连接
    QSqlDatabase db = getDatabase();
    if (!db.isValid()) {
        errorMessages << "数据库连接无效";
    } else if (!db.isOpen()) {
        errorMessages << "数据库未打开";
    }

    // 检查被试信息完整性
    if (subjectInfo.isEmpty()) {
        errorMessages << "无法获取被试信息";
    } else {
        if (subjectInfo["name"].isEmpty()) {
            errorMessages << "被试姓名为空，请先录入被试基本信息";
        }
        if (subjectInfo["gender"].isEmpty()) {
            errorMessages << "被试性别未设置，请完善被试基本信息";
        }
        if (subjectInfo["age"].isEmpty() || subjectInfo["age"] == "0") {
            errorMessages << "被试年龄信息缺失，请完善被试基本信息";
        }
    }

    // 检查当前被试ID
    int currentSubjectId = getCurrentSubjectId();
    //int currentSubjectId = 1;

    if (currentSubjectId <= 0) {
        errorMessages << "无法确定当前被试ID，请确保已选择有效的被试";
    }

    // 注释掉测试数据检查部分，允许在没有测试分数的情况下生成报告
    /*
    // 检查测试数据
    if (testScores.isEmpty()) {
        errorMessages << "无法获取测试分数数据";
    } else {
        int recordNum = getCurrentRecordNum();
        double currentScore = getCurrentTestScore(testScores, recordNum);

        if (currentScore < 0.0) {
            errorMessages << QString("第%1次测试尚未完成或分数无效，请先完成当前测试").arg(recordNum);
        }
    }
    */

    // 检查必要的数据表是否存在
    if (db.isValid() && db.isOpen()) {
        QSqlQuery query(db);

        // 检查subjects表
        query.exec("SELECT name FROM sqlite_master WHERE type='table' AND name='subjects'");
        if (!query.next()) {
            errorMessages << "被试信息表(subjects)不存在，请检查数据库结构";
        }

        // 注释掉测试分数表检查，允许在没有测试分数表的情况下生成报告
        /*
        // 检查test_scores表或相关分析结果表
        query.exec("SELECT name FROM sqlite_master WHERE type='table' AND name='test_scores'");
        bool hasTestScores = query.next();

        query.exec("SELECT name FROM sqlite_master WHERE type='table' AND name='analysis_results'");
        bool hasAnalysisResults = query.next();

        if (!hasTestScores && !hasAnalysisResults) {
            errorMessages << "测试分数表不存在，请确保已进行过分析测试";
        }
        */
    }

    // 如果有错误，显示详细错误信息
    if (!errorMessages.isEmpty()) {
        QString detailedError = "报告生成失败，原因如下：\n\n";
        for (int i = 0; i < errorMessages.size(); ++i) {
            detailedError += QString("%1. %2\n").arg(i + 1).arg(errorMessages[i]);
        }
        detailedError += "\n请解决以上问题后重新尝试生成报告。";

        // 显示详细错误信息
        QMessageBox::warning(nullptr, "数据验证失败", detailedError);
        return false;
    }

    return true;
}

// 获取当前测试次数
int AnalysisWidget::getCurrentRecordNum() {
    // 从数据库或配置中获取当前测试次数
    QSqlDatabase db = getDatabase();
    if (!db.isValid() || !db.isOpen()) {
        qDebug() << "getCurrentRecordNum: 数据库连接失败，返回默认值1";
        return 1; // 默认第1次
    }

    int currentSubjectId = getCurrentSubjectId();
    //int currentSubjectId = 1;

    if (currentSubjectId <= 0) {
        qDebug() << "getCurrentRecordNum: 当前被试ID无效，返回默认值1";
        return 1;
    }

    QSqlQuery query(db);
    query.prepare("SELECT COUNT(*) FROM test_scores WHERE subject_id = ? AND score >= 0");
    query.addBindValue(currentSubjectId);

    if (query.exec() && query.next()) {
        int count = query.value(0).toInt();
        return count + 1; // 下一次测试
    } else {
        qDebug() << "getCurrentRecordNum: 查询失败或无记录，返回默认值1";
        return 1;
    }
}

// 获取当前测试分数
double AnalysisWidget::getCurrentTestScore(const QMap<QString, double>& testScores, int recordNum) {
    switch (recordNum) {
    case 1: return testScores.value("first_score", -1.0);
    case 2: return testScores.value("second_score", -1.0);
    case 3: return testScores.value("third_score", -1.0);
    case 4: return testScores.value("fourth_score", -1.0);
    case 5: return testScores.value("fifth_score", -1.0);
    default: return -1.0;
    }
}

// 计算结果类型（按照Python程序逻辑）
int AnalysisWidget::calculateResultType(double score) {
    if (score < 0) return -1; // 无效分数
    if (score < 45) return 0; // 健康
    if (score < 65) return 1; // 轻度抑郁
    if (score < 75) return 2; // 中度抑郁
    return 3; // 重度抑郁
}

QPoint convertPtToPx(double xPt, double yPt, double pageHeightPx=3508) {
    yPt -= 43;
    constexpr double dpi = 300.0;
    constexpr double pxPerPt = dpi / 72.0;  // = 4.16666...

    int x = static_cast<int>(xPt * pxPerPt);
    int y = static_cast<int>(pageHeightPx - yPt * pxPerPt);  // y 轴翻转

    return QPoint(x, y);
}

int convertYPtToPx(double yPt, double pageHeightPx=3508) {
    yPt -= 43;
    constexpr double dpi = 300.0;
    constexpr double pxPerPt = dpi / 72.0;  // = 4.16666...

    int y = static_cast<int>(pageHeightPx - yPt * pxPerPt);  // y 轴翻转

    return y;
}



// 绘制背景模板
void AnalysisWidget::drawBackgroundTemplate(QPainter& painter, const QString& gender) {
    QRectF pageRect = painter.device()->logicalDpiX() > 0 ?
                          QRectF(0, 0, painter.device()->width(), painter.device()->height()) :
                          QRectF(0, 0, 2480, 3508); // A4 at 300 DPI

    // 根据性别选择背景图片
    QString backgroundPath;
    if (gender == "女" || gender == "Female") {
        backgroundPath = ":/resources/model_female.png";
    } else {
        backgroundPath = ":/resources/model_male.png";
    }

    QPixmap background(backgroundPath);
    if (!background.isNull()) {
        painter.drawPixmap(pageRect.toRect(), background);
    } else {
        // 如果背景图片不存在，绘制默认背景
        painter.fillRect(pageRect, QColor(240, 240, 255));
    }
}

// 绘制基本信息
void AnalysisWidget::drawBasicInfo(QPainter& painter, int& yPos, const QMap<QString, QString>& subjectInfo) {
    // 设置字体
    QFont font("Microsoft YaHei", 14);
    painter.setFont(font);
    painter.setPen(Qt::black);

    // 绘制基本信息（坐标参考Python程序）
    painter.drawText(convertPtToPx(220, 663), subjectInfo.value("number", ""));
    painter.drawText(convertPtToPx(374 , 663), subjectInfo.value("name", ""));
    painter.drawText(convertPtToPx(527 , 663), subjectInfo.value("gender", ""));
    painter.drawText(convertPtToPx(222, 631), subjectInfo.value("age", ""));
    painter.drawText(convertPtToPx(246, 599), subjectInfo.value("time", ""));

    yPos += 100;
}

// 绘制当前测试结果
void AnalysisWidget::drawCurrentTestResult(QPainter& painter, int& yPos, double score, int resultType) {
    QFont font("Microsoft YaHei", 19);
    painter.setFont(font);

    // 如果分数无效，使用默认显示
    if (score < 0) {
        score = 0.0; // 显示0分
        resultType = -1; // 设置为无效类型
    }

    // 绘制分数
    painter.drawText(convertPtToPx(168, 451), QString::number(score, 'f', 1));
    painter.drawText(convertPtToPx(218, 451), "%");

    // 绘制结果类型和箭头
    QString resultText;
    QString arrowPath;

    switch (resultType) {
    case 0:
        resultText = "健  康";
        arrowPath = "D:/data/project/prjct2025/QT/1.1.1(1)/resources/箭头0.png";
        break;
    case 1:
        resultText = "轻 度 抑 郁";
        arrowPath = "D:/data/project/prjct2025/QT/1.1.1(1)/resources/箭头1.png";
        break;
    case 2:
        resultText = "中 度 抑 郁";
        arrowPath = "D:/data/project/prjct2025/QT/1.1.1(1)/resources/箭头2.png";
        break;
    case 3:
        resultText = "重 度 抑 郁";
        arrowPath = "D:/data/project/prjct2025/QT/1.1.1(1)/resources/箭头3.png";
        break;
    default:
        resultText = "待 测 试";
        arrowPath = "D:/data/project/prjct2025/QT/1.1.1(1)/resources/箭头0.png"; // 使用默认箭头
        break;
    }

    painter.drawText(convertPtToPx(131, 423), resultText);

    // 绘制箭头
    QPixmap arrow(arrowPath);
    if (!arrow.isNull()) {
        int arrowX;
        if (score >= 0) {
            arrowX = (479 - 72) / 100.0 * score + 72;
        } else {
            arrowX = 72; // 默认位置
        }
        painter.drawPixmap(arrowX * 4.2, convertYPtToPx(410), 10 * 4.2, 19 * 4.2, arrow);
    }
    yPos = 410 - 100;
}

// 绘制扇形图
void AnalysisWidget::drawSectorChart(QPainter& painter, int& yPos, const QMap<QString, double>& testScores, int recordNum) {
    // 扇形图参数
    int centerX = 435;
    int centerY = 556 + 94;
    int radius = 42;
    int sectorWidth = 30;

    // 角度计算
    double sin36 = qSin(qDegreesToRadians(36.0));
    double cos36 = qCos(qDegreesToRadians(36.0));
    double sin18 = qSin(qDegreesToRadians(18.0));
    double cos18 = qCos(qDegreesToRadians(18.0));

    // 默认和当前扇形的离心距离
    int defaultOffset = 2;
    int currentOffset = 10;

    QFont font("Microsoft YaHei", 6);
    painter.setFont(font);

    // 绘制5个扇形
    QVector<double> scores = {
        testScores.value("first_score", -1.0),
        testScores.value("second_score", -1.0),
        testScores.value("third_score", -1.0),
        testScores.value("fourth_score", -1.0),
        testScores.value("fifth_score", -1.0)
    };

    QVector<QPointF> offsets = {
        QPointF(sin36, cos36),
        QPointF(cos18, -sin18),
        QPointF(0, -1),
        QPointF(-cos18, -sin18),
        QPointF(-sin36, cos36)
    };

    for (int i = 0; i < 5; i++) {
        double score = scores[i];
        QString color = getScoreColor(score);

        // 确定偏移量 - 如果没有有效分数，不突出显示任何扇形
        int offset = defaultOffset;
        if (score >= 0 && (i + 1 == recordNum)) {
            offset = currentOffset;
        }

        // 计算扇形位置
        QPointF offsetPoint = offsets[i] * offset;
        int sectorX = centerX + offsetPoint.x();
        int sectorY = centerY + offsetPoint.y();

        // 设置扇形颜色
        painter.setPen(QPen(QColor(color), sectorWidth * 4.2));

        // 绘制扇形
        QRect sectorRect((sectorX - radius) * 4.2, convertYPtToPx(sectorY - radius), 2 * radius * 5, 2 * radius * 5);
        int startAngle = 90 + 72 * (4 - i); // 角度转换
        painter.drawArc(sectorRect, startAngle * 16, 90 * 16); // Qt使用1/16度

        // 绘制测试次数标签
        QString label = QString("第%1次检测").arg(i + 1);
        QPointF labelPos = calculateLabelPosition(centerX * 4.2, convertYPtToPx(centerY), i, offset);
        painter.drawText(labelPos, label);
    }

    // 绘制中心的测试次数 - 如果没有有效分数，显示"待测试"
    QFont boldFont("Microsoft YaHei", 20, QFont::Bold);
    painter.setFont(boldFont);

    bool hasValidScore = false;
    for (double score : scores) {
        if (score >= 0) {
            hasValidScore = true;
            break;
        }
    }

    if (hasValidScore) {
        painter.drawText(convertPtToPx(453, 556), QString::number(recordNum));
    } else {
        QFont smallFont("Microsoft YaHei", 12, QFont::Bold);
        painter.setFont(smallFont);
        painter.drawText(convertPtToPx(430, 556), "待测试");
    }
}

// 获取分数对应的颜色
QString AnalysisWidget::getScoreColor(double score) {
    if (score < 0) return "#D0CECE"; // 未测试
    if (score < 45) return "#30BB50"; // 健康
    if (score < 65) return "#A8D08D"; // 轻度
    if (score < 75) return "#FFD966"; // 中度
    return "#FF0000"; // 重度
}

// 计算标签位置
QPointF AnalysisWidget::calculateLabelPosition(int centerX, int centerY, int index, int offset) {
    // 根据扇形位置计算标签位置
    QVector<QPointF> labelOffsets = {
        QPointF(17, -9),   // 第1次
        QPointF(35, 15),   // 第2次
        QPointF(-13, 52),  // 第3次
        QPointF(-63, 15),  // 第4次
        QPointF(-45, -9)   // 第5次
    };

    return QPointF(convertPtToPx(centerX + labelOffsets[index].x(), centerY + labelOffsets[index].y()));
}

// 从数据库绘制波形数据
void AnalysisWidget::drawWaveformsFromDB(QPainter& painter, int& yPos) {
    // 获取波形数据
    QMap<QString, QVector<QPair<qint64, double>>> waveformData = getWaveformDataFromDB();

    // 应用滤波处理（模拟Python中的信号处理）
    QMap<QString, QVector<double>> filteredData = applyBandpassFilter(waveformData);

    yPos -= 84;

    // 绘制三个波形图
    drawSingleWaveform(painter, yPos, filteredData["EEG"], QColor(237, 31, 36), "EEG波形");
    drawSingleWaveform(painter, yPos, filteredData["ECG"], QColor(12, 128, 64), "ECG波形");
    drawSingleWaveform(painter, yPos, filteredData["GSR"], QColor(250, 166, 27), "GSR波形");
}

// 应用带通滤波器
QMap<QString, QVector<double>> AnalysisWidget::applyBandpassFilter(const QMap<QString, QVector<QPair<qint64, double>>>& rawData) {
    QMap<QString, QVector<double>> filteredData;

    // 模拟Python中的巴特沃斯滤波器处理
    for (auto it = rawData.constBegin(); it != rawData.constEnd(); ++it) {
        QString channel = it.key();
        const QVector<QPair<qint64, double>>& data = it.value();

        QVector<double> values;
        for (const auto& point : data) {
            values.append(point.second);
        }

        // 简单的滤波处理（实际应用中应使用专业的信号处理库）
        QVector<double> filtered = simpleBandpassFilter(values, 200.0, 1.0, 75.0);
        filteredData[channel] = filtered;
    }

    return filteredData;
}

// 简单带通滤波器实现
QVector<double> AnalysisWidget::simpleBandpassFilter(const QVector<double>& input, double fs, double lowFreq, double highFreq) {
    // 这里实现一个简化的带通滤波器
    // 实际项目中应使用专业的信号处理库如DSP库
    QVector<double> output = input;

    // 简单的移动平均滤波
    int windowSize = qMax(3, static_cast<int>(fs / (2 * highFreq)));
    for (int i = windowSize; i < output.size() - windowSize; i++) {
        double sum = 0;
        for (int j = -windowSize/2; j <= windowSize/2; j++) {
            sum += input[i + j];
        }
        output[i] = sum / (windowSize + 1);
    }

    return output;
}

// 绘制单个波形
void AnalysisWidget::drawSingleWaveform(QPainter& painter, int& yPos, const QVector<double>& data, const QColor& color, const QString& title) {
    if (data.isEmpty()) return;

    int waveformHeight = 40;
    int waveformWidth = 480;
    int margin = 50;

    // 绘制标题
    QFont titleFont("Microsoft YaHei", 10, QFont::Bold);
    painter.setFont(titleFont);
    painter.setPen(Qt::black);
    painter.drawText(convertPtToPx(margin, yPos), title);
    yPos -= 6;

    // 绘制波形框
    QRect waveRect(margin*4.2, convertYPtToPx(yPos), waveformWidth * 4.2, waveformHeight * 4.2);
    painter.fillRect(waveRect, QColor(240, 240, 255, 100));
    painter.drawRect(waveRect);

    // 绘制波形数据
    painter.setPen(QPen(color, 2));

    // 取数据的中间部分（模拟Python中的[3000:4500]）
    int startIdx = qMax(0, data.size() / 3);
    int endIdx = qMin(data.size(), startIdx + 1500);

    if (endIdx > startIdx) {
        // 找到数据范围用于归一化
        double minVal = *std::min_element(data.begin() + startIdx, data.begin() + endIdx);
        double maxVal = *std::max_element(data.begin() + startIdx, data.begin() + endIdx);

        if (qAbs(maxVal - minVal) > 1e-6) {
            double scale = waveformHeight * 0.8 / (maxVal - minVal);
            double centerY = yPos - waveformHeight / 2.0;

            // 绘制波形
            for (int i = startIdx + 1; i < endIdx; i++) {
                double x1 = margin + (i - startIdx - 1) * waveformWidth / double(endIdx - startIdx - 1);
                double y1 = centerY - (data[i - 1] - (maxVal + minVal) / 2) * scale;
                double x2 = margin + (i - startIdx) * waveformWidth / double(endIdx - startIdx - 1);
                double y2 = centerY - (data[i] - (maxVal + minVal) / 2) * scale;

                painter.drawLine(QPointF(convertPtToPx(x1, y1)), QPointF(convertPtToPx(x2, y2)));
            }
        }
    }

    yPos -= waveformHeight + 10;
}

// 绘制第二页背景
void AnalysisWidget::drawResultBackground(QPainter& painter, int resultType) {
    QRectF pageRect(0, 0, painter.device()->width(), painter.device()->height());

    QString backgroundPath;
    switch (resultType) {
    case 0: backgroundPath = "D:/data/project/prjct2025/QT/1.1.1(1)/resources/model_0.png"; break;
    case 1: backgroundPath = "D:/data/project/prjct2025/QT/1.1.1(1)/resources/model_1.png"; break;
    case 2: backgroundPath = "D:/data/project/prjct2025/QT/1.1.1(1)/resources/model_2.png"; break;
    case 3: backgroundPath = "D:/data/project/prjct2025/QT/1.1.1(1)/resources/model_3.png"; break;
    default: backgroundPath = "D:/data/project/prjct2025/QT/1.1.1(1)/resources/model_0.png"; break;
    }

    QPixmap background(backgroundPath);
    if (!background.isNull()) {
        painter.drawPixmap(pageRect.toRect(), background);
    }
}

// 获取当前被试ID
int AnalysisWidget::getCurrentSubjectId() {
    // 首先尝试通过DatabaseManager获取
    DatabaseManager* dbManager = DatabaseManager::getInstance();
    if (dbManager) {
        int subjectId = dbManager->getCurrentSubjectId();
        if (subjectId > 0) {
            return subjectId;
        }
    }

    // 如果DatabaseManager不可用，直接查询数据库
    QSqlDatabase db = getDatabase();
    if (!db.isValid() || !db.isOpen()) {
        return -1;
    }

    QSqlQuery query(db);
    query.exec("SELECT current_subject_id FROM settings WHERE id = 1");
    if (query.next()) {
        return query.value(0).toInt();
    }

    // 如果没有设置表，尝试获取最新的被试ID
    query.exec("SELECT id FROM subjects ORDER BY id DESC LIMIT 1");
    if (query.next()) {
        return query.value(0).toInt();
    }

    return -1;
}

// 原有的其他方法保持不变...
void AnalysisWidget::drawLogo(QPainter &painter, int &yPos) {
    int margin = 50;
    int pageWidth = painter.device()->width();

    // Logo区域 - 左上角
    QRect logoRect(margin * 4.2, convertYPtToPx(yPos), 150, 60);

    // 如果有Logo图片，则绘制Logo
    QPixmap logo(":/images/logo.png");

    if (!logo.isNull()) {
        logo = logo.scaled(logoRect.size(), Qt::KeepAspectRatio, Qt::SmoothTransformation);
        painter.drawPixmap(logoRect.x(), logoRect.y(), logo);
    } else {
        painter.drawText(logoRect, Qt::AlignCenter, "公司Logo");
        painter.drawRect(logoRect);
    }

    yPos += 80;
}

// void AnalysisWidget::drawReportHeader(QPainter &painter, int &yPos, const QMap<QString, QString> &subjectInfo) {
//     int margin = 50;
//     int pageWidth = painter.device()->width();

//     // 绘制个人信息表格
//     QRect infoRect(margin, yPos, pageWidth - 2*margin, 160);
//     painter.drawRect(infoRect);

//     // 表格分隔线
//     int colWidth = (pageWidth - 2*margin) / 2;
//     int rowHeight = 40;

//     painter.drawLine(margin + colWidth, yPos, margin + colWidth, yPos + 160);
//     painter.drawLine(margin, yPos + rowHeight, margin + 2*colWidth, yPos + rowHeight);
//     painter.drawLine(margin, yPos + 2*rowHeight, margin + 2*colWidth, yPos + 2*rowHeight);
//     painter.drawLine(margin, yPos + 3*rowHeight, margin + 2*colWidth, yPos + 3*rowHeight);

//     // 填充信息
//     QFont boldFont = painter.font();
//     boldFont.setBold(true);
//     boldFont.setPointSize(14);
//     QFont normalFont = painter.font();

//     // 姓名和性别
//     painter.setFont(boldFont);
//     painter.drawText(margin + 15, yPos + 5, colWidth - 30, rowHeight - 10, Qt::AlignLeft | Qt::AlignVCenter, "姓名:");
//     painter.setFont(normalFont);
//     painter.drawText(margin + 70, yPos + 5, colWidth - 80, rowHeight - 10, Qt::AlignLeft | Qt::AlignVCenter, subjectInfo["name"]);

//     painter.setFont(boldFont);
//     painter.drawText(margin + colWidth + 15, yPos + 5, colWidth - 30, rowHeight - 10, Qt::AlignLeft | Qt::AlignVCenter, "性别:");
//     painter.setFont(normalFont);
//     painter.drawText(margin + colWidth + 70, yPos + 5, colWidth - 80, rowHeight - 10, Qt::AlignLeft | Qt::AlignVCenter, subjectInfo["gender"]);

//     // 年龄和检测时间
//     painter.setFont(boldFont);
//     painter.drawText(margin + 15, yPos + rowHeight + 5, colWidth - 30, rowHeight - 10, Qt::AlignLeft | Qt::AlignVCenter, "年龄:");
//     painter.setFont(normalFont);
//     painter.drawText(margin + 70, yPos + rowHeight + 5, colWidth - 80, rowHeight - 10, Qt::AlignLeft | Qt::AlignVCenter, subjectInfo["age"] + "岁");

//     painter.setFont(boldFont);
//     painter.drawText(margin + colWidth + 15, yPos + rowHeight + 5, colWidth - 30, rowHeight - 10, Qt::AlignLeft | Qt::AlignVCenter, "检测时间:");
//     painter.setFont(normalFont);
//     painter.drawText(margin + colWidth + 70, yPos + rowHeight + 5, colWidth - 80, rowHeight - 10, Qt::AlignLeft | Qt::AlignVCenter, subjectInfo["time"]);

//     // 检测编号和检测地点
//     painter.setFont(boldFont);
//     painter.drawText(margin + 15, yPos + 2*rowHeight + 5, colWidth - 30, rowHeight - 10, Qt::AlignLeft | Qt::AlignVCenter, "检测编号:");
//     painter.setFont(normalFont);
//     painter.drawText(margin + 70, yPos + 2*rowHeight + 5, colWidth - 80, rowHeight - 10, Qt::AlignLeft | Qt::AlignVCenter, subjectInfo["id"]);

//     painter.setFont(boldFont);
//     painter.drawText(margin + colWidth + 15, yPos + 2*rowHeight + 5, colWidth - 30, rowHeight - 10, Qt::AlignLeft | Qt::AlignVCenter, "检测地点:");
//     painter.setFont(normalFont);
//     painter.drawText(margin + colWidth + 70, yPos + 2*rowHeight + 5, colWidth - 80, rowHeight - 10, Qt::AlignLeft | Qt::AlignVCenter, subjectInfo["location"]);

//     // 检测医生和备注
//     painter.setFont(boldFont);
//     painter.drawText(margin + 15, yPos + 3*rowHeight + 5, colWidth - 30, rowHeight - 10, Qt::AlignLeft | Qt::AlignVCenter, "检测医生:");
//     painter.setFont(normalFont);
//     painter.drawText(margin + 70, yPos + 3*rowHeight + 5, colWidth - 80, rowHeight - 10, Qt::AlignLeft | Qt::AlignVCenter, subjectInfo["doctor"]);

//     painter.setFont(boldFont);
//     painter.drawText(margin + colWidth + 15, yPos + 3*rowHeight + 5, colWidth - 30, rowHeight - 10, Qt::AlignLeft | Qt::AlignVCenter, "备注:");
//     painter.setFont(normalFont);
//     painter.drawText(margin + colWidth + 70, yPos + 3*rowHeight + 5, colWidth - 80, rowHeight - 10, Qt::AlignLeft | Qt::AlignVCenter, subjectInfo["note"]);

//     yPos += 180;
// }

void AnalysisWidget::drawWaveforms(QPainter &painter, int &yPos) {
    int margin = 50;
    int pageWidth = painter.device()->width();
    int maxHeight = painter.device()->height();

    // 为三种波形预留空间
    int waveformHeight = 140;
    int waveformSpacing = 50;

    // 从数据库获取波形数据
    QMap<QString, QVector<QPair<qint64, double>>> waveformData = getWaveformDataFromDB();

    // 检查是否需要新页面
    if (yPos + waveformHeight + 30 > maxHeight - margin) {
        painter.save();
        painter.restore();
        yPos = 50;
        drawLogo(painter, yPos);
    }

    // 绘制EEG波形
    QFont boldFont = painter.font();
    boldFont.setBold(true);
    boldFont.setPointSize(14);
    painter.setFont(boldFont);

    // 添加EEG图标
    QPixmap eegIcon(":/images/eeg_icon.png");
    if (!eegIcon.isNull()) {
        eegIcon = eegIcon.scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation);
        painter.drawPixmap(margin, yPos, eegIcon);
        painter.drawText(margin + 40, yPos, pageWidth - 2*margin - 40, 30, Qt::AlignLeft | Qt::AlignVCenter, "EEG波形");
    } else {
        painter.drawText(margin, yPos, pageWidth - 2*margin, 30, Qt::AlignLeft, "EEG波形");
    }
    yPos += 30;

    // 绘制EEG波形图框
    QRect eegRect(margin, yPos, pageWidth - 2*margin, waveformHeight);
    painter.fillRect(eegRect, QColor(240, 240, 255));
    painter.drawRect(eegRect);

    // 绘制实际EEG波形
    QPen wavePen(Qt::blue);
    wavePen.setWidth(2);
    painter.setPen(wavePen);

    int waveWidth = pageWidth - 2*margin - 20;
    int waveCenter = yPos + waveformHeight/2;

    // 使用实际数据绘制EEG波形
    if (waveformData.contains("EEG") && !waveformData["EEG"].isEmpty()) {
        const QVector<QPair<qint64, double>> &eegData = waveformData["EEG"];

        // 找到数据的最小和最大值，用于归一化
        double minValue = eegData.first().second;
        double maxValue = eegData.first().second;
        for (const auto &point : eegData) {
            minValue = qMin(minValue, point.second);
            maxValue = qMax(maxValue, point.second);
        }

        // 如果最大值和最小值相同，避免除以零
        if (qFuzzyCompare(maxValue, minValue)) {
            maxValue = minValue + 1.0;
        }

        // 计算缩放因子
        double amplitude = waveformHeight / 2.5;
        double scaleFactor = amplitude / ((maxValue - minValue) / 2.0);

        // 绘制波形
        painter.setPen(Qt::blue);
        int lastX = margin + 10;
        double lastY = waveCenter - (eegData.first().second - ((maxValue + minValue) / 2.0)) * scaleFactor;

        // 计算X轴缩放因子
        double xScale = static_cast<double>(waveWidth) / eegData.size();

        for (int i = 1; i < eegData.size(); ++i) {
            int x = margin + 10 + i * xScale;
            double y = waveCenter - (eegData[i].second - ((maxValue + minValue) / 2.0)) * scaleFactor;

            painter.drawLine(lastX, lastY, x, y);
            lastX = x;
            lastY = y;
        }

        // 添加刻度和标签
        painter.setPen(Qt::black);
        QFont smallerFont = painter.font();
        smallerFont.setPointSize(smallerFont.pointSize() - 2);
        painter.setFont(smallerFont);

        // X轴刻度
        for (int i = 0; i <= 5; i++) {
            int x = margin + 10 + (waveWidth * i / 5);
            painter.drawLine(x, yPos + waveformHeight - 5, x, yPos + waveformHeight);
            painter.drawText(x - 15, yPos + waveformHeight + 5, 30, 20, Qt::AlignCenter,
                             QString::number(i * eegData.size() / 5) + "ms");
        }

        // Y轴刻度
        for (int i = 0; i <= 4; i++) {
            int y = yPos + 10 + (waveformHeight - 20) * i / 4;
            painter.drawLine(margin, y, margin + 5, y);
            double value = maxValue - (i * (maxValue - minValue) / 4);
            painter.drawText(margin - 40, y - 10, 35, 20, Qt::AlignRight | Qt::AlignVCenter,
                             QString::number(value, 'f', 1) + "μV");
        }

        painter.setFont(boldFont);
    } else {
        // 如果没有数据，显示提示信息
        painter.setPen(Qt::black);
        painter.drawText(eegRect, Qt::AlignCenter, "无EEG数据可用");
    }

    yPos += waveformHeight + waveformSpacing;

    // 检查是否需要新页面
    if (yPos + waveformHeight + 30 > maxHeight - margin) {
        painter.save();
        painter.restore();
        yPos = 50;
        drawLogo(painter, yPos);
    }

    // 绘制ECG波形
    painter.setFont(boldFont);
    painter.setPen(Qt::black);

    // 添加ECG图标
    QPixmap ecgIcon(":/images/ecg_icon.png");
    if (!ecgIcon.isNull()) {
        ecgIcon = ecgIcon.scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation);
        painter.drawPixmap(margin * 4.2, convertYPtToPx(yPos), ecgIcon);
        painter.drawText((margin + 40) * 4.2, convertYPtToPx(yPos), pageWidth - 2*margin - 40, 30, Qt::AlignLeft | Qt::AlignVCenter, "ECG波形");
    } else {
        painter.drawText(margin * 4.2, convertYPtToPx(yPos), pageWidth - 2*margin, 30, Qt::AlignLeft, "ECG波形");
    }
    yPos += 30;

    QRect ecgRect(margin * 4.2, convertYPtToPx(yPos), pageWidth - 2*margin, waveformHeight);
    painter.fillRect(ecgRect, QColor(255, 240, 240));
    painter.drawRect(ecgRect);

    // 绘制实际ECG波形
    wavePen.setColor(Qt::red);
    painter.setPen(wavePen);
    waveCenter = yPos + waveformHeight/2;

    // 使用实际数据绘制ECG波形
    if (waveformData.contains("ECG") && !waveformData["ECG"].isEmpty()) {
        const QVector<QPair<qint64, double>> &ecgData = waveformData["ECG"];

        // 找到数据的最小和最大值，用于归一化
        double minValue = ecgData.first().second;
        double maxValue = ecgData.first().second;
        for (const auto &point : ecgData) {
            minValue = qMin(minValue, point.second);
            maxValue = qMax(maxValue, point.second);
        }

        // 如果最大值和最小值相同，避免除以零
        if (qFuzzyCompare(maxValue, minValue)) {
            maxValue = minValue + 1.0;
        }

        // 计算缩放因子
        double amplitude = waveformHeight / 2.5;
        double scaleFactor = amplitude / ((maxValue - minValue) / 2.0);

        // 绘制波形
        painter.setPen(Qt::red);
        int lastX = margin + 10;
        double lastY = waveCenter - (ecgData.first().second - ((maxValue + minValue) / 2.0)) * scaleFactor;

        // 计算X轴缩放因子
        double xScale = static_cast<double>(waveWidth) / ecgData.size();

        for (int i = 1; i < ecgData.size(); ++i) {
            int x = margin + 10 + i * xScale;
            double y = waveCenter - (ecgData[i].second - ((maxValue + minValue) / 2.0)) * scaleFactor;

            painter.drawLine(lastX, convertYPtToPx(lastY), x, convertYPtToPx(y));
            lastX = x;
            lastY = y;
        }

        // 添加刻度和标签
        painter.setPen(Qt::black);
        QFont smallerFont = painter.font();
        smallerFont.setPointSize(smallerFont.pointSize() - 2);
        painter.setFont(smallerFont);
        // X轴刻度
        for (int i = 0; i <= 5; i++) {
            int x = margin + 10 + (waveWidth * i / 5);
            painter.drawLine(x, convertYPtToPx(yPos + waveformHeight - 5), x, convertYPtToPx(yPos + waveformHeight));
            painter.drawText(x - 15, convertYPtToPx(yPos + waveformHeight + 5), 30, 20, Qt::AlignCenter,
                             QString::number(i * ecgData.size() / 5) + "ms");
        }

        // Y轴刻度
        for (int i = 0; i <= 4; i++) {
            int y = yPos + 10 + (waveformHeight - 20) * i / 4;
            painter.drawLine(margin, convertYPtToPx(y), margin + 5, convertYPtToPx(y));
            double value = maxValue - (i * (maxValue - minValue) / 4);
            painter.drawText(margin - 40, convertYPtToPx(y - 10), 35, 20, Qt::AlignRight | Qt::AlignVCenter,
                             QString::number(value, 'f', 1) + "mV");
        }

        painter.setFont(boldFont);
    } else {
        // 如果没有数据，显示提示信息
        painter.setPen(Qt::black);
        painter.drawText(ecgRect, Qt::AlignCenter, "无ECG数据可用");
    }

    yPos += waveformHeight + waveformSpacing;

    // 检查是否需要新页面
    if (yPos + waveformHeight + 30 > maxHeight - margin) {
        painter.save();
        painter.restore();
        yPos = convertYPtToPx(50);
        drawLogo(painter, yPos);
    }

    // 绘制GSR波形
    painter.setFont(boldFont);
    painter.setPen(Qt::black);

    // 添加GSR图标
    QPixmap gsrIcon(":/images/gsr_icon.png");
    if (!gsrIcon.isNull()) {
        gsrIcon = gsrIcon.scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation);
        painter.drawPixmap(margin, yPos, gsrIcon);
        painter.drawText(margin + 40, yPos, pageWidth - 2*margin - 40, 30, Qt::AlignLeft | Qt::AlignVCenter, "GSR波形");
    } else {
        painter.drawText(margin, yPos, pageWidth - 2*margin, 30, Qt::AlignLeft, "GSR波形");
    }
    yPos += 30;

    QRect gsrRect(margin, yPos, pageWidth - 2*margin, waveformHeight);
    painter.fillRect(gsrRect, QColor(240, 255, 240));
    painter.drawRect(gsrRect);

    // 绘制实际GSR波形
    wavePen.setColor(Qt::green);
    painter.setPen(wavePen);
    waveCenter = yPos + waveformHeight/2;

    // 使用实际数据绘制GSR波形
    if (waveformData.contains("GSR") && !waveformData["GSR"].isEmpty()) {
        const QVector<QPair<qint64, double>> &gsrData = waveformData["GSR"];

        // 找到数据的最小和最大值，用于归一化
        double minValue = gsrData.first().second;
        double maxValue = gsrData.first().second;
        for (const auto &point : gsrData) {
            minValue = qMin(minValue, point.second);
            maxValue = qMax(maxValue, point.second);
        }

        // 如果最大值和最小值相同，避免除以零
        if (qFuzzyCompare(maxValue, minValue)) {
            maxValue = minValue + 1.0;
        }

        // 计算缩放因子
        double amplitude = waveformHeight / 2.5;
        double scaleFactor = amplitude / ((maxValue - minValue) / 2.0);

        // 绘制波形
        painter.setPen(Qt::green);
        int lastX = margin + 10;
        double lastY = waveCenter - (gsrData.first().second - ((maxValue + minValue) / 2.0)) * scaleFactor;

        // 计算X轴缩放因子
        double xScale = static_cast<double>(waveWidth) / gsrData.size();

        for (int i = 1; i < gsrData.size(); ++i) {
            int x = margin + 10 + i * xScale;
            double y = waveCenter - (gsrData[i].second - ((maxValue + minValue) / 2.0)) * scaleFactor;

            painter.drawLine(lastX, lastY, x, y);
            lastX = x;
            lastY = y;
        }

        // 添加刻度和标签
        painter.setPen(Qt::black);
        QFont smallerFont = painter.font();
        smallerFont.setPointSize(smallerFont.pointSize() - 2);
        painter.setFont(smallerFont);
        // X轴刻度
        for (int i = 0; i <= 5; i++) {
            int x = margin + 10 + (waveWidth * i / 5);
            painter.drawLine(x, yPos + waveformHeight - 5, x, yPos + waveformHeight);
            painter.drawText(x - 15, yPos + waveformHeight + 5, 30, 20, Qt::AlignCenter,
                             QString::number(i * gsrData.size() / 5) + "ms");
        }

        // Y轴刻度
        for (int i = 0; i <= 4; i++) {
            int y = yPos + 10 + (waveformHeight - 20) * i / 4;
            painter.drawLine(margin, y, margin + 5, y);
            double value = maxValue - (i * (maxValue - minValue) / 4);
            painter.drawText(margin - 40, y - 10, 35, 20, Qt::AlignRight | Qt::AlignVCenter,
                             QString::number(value, 'f', 1) + "μS");
        }

        painter.setFont(boldFont);
    } else {
        // 如果没有数据，显示提示信息
        painter.setPen(Qt::black);
        painter.drawText(gsrRect, Qt::AlignCenter, "无GSR数据可用");
    }

    yPos += waveformHeight + waveformSpacing;
}

// void AnalysisWidget::drawAnalysisResults(QPainter &painter, int &yPos) {
//     int margin = 50;
//     int pageWidth = painter.device()->width();
//     int maxHeight = painter.device()->height();

//     // 检查是否需要新页面
//     if (yPos + 200 > maxHeight - margin) {
//         painter.save();
//         painter.restore();
//         yPos = 50;
//         drawLogo(painter, yPos);
//     }

//     // 获取分析结果
//     QMap<QString, double> results = getAnalysisResults();

//     // 增加行高以提供更多空间
//     int rowHeight = 50;
//     int tableHeight = (results.size() + 1) * rowHeight;

//     // 添加表格背景色
//     QRect tableRect(margin, yPos, pageWidth - 2*margin, tableHeight);
//     painter.fillRect(tableRect, QColor(245, 245, 250));
//     painter.drawRect(tableRect);

//     // 绘制表头
//     QFont boldFont = painter.font();
//     boldFont.setBold(true);
//     boldFont.setPointSize(14);
//     painter.setFont(boldFont);

//     // 表头背景
//     QRect headerRect(margin, yPos, pageWidth - 2*margin, rowHeight);
//     painter.fillRect(headerRect, QColor(220, 220, 240));

//     // 增加列宽，使表格更宽
//     int colWidth = (pageWidth - 2*margin) / 3;
//     painter.drawText(margin + 10, yPos, colWidth - 20, rowHeight, Qt::AlignCenter, "评估项目");
//     painter.drawText(margin + colWidth + 10, yPos, colWidth - 20, rowHeight, Qt::AlignCenter, "评估结果");
//     painter.drawText(margin + 2*colWidth + 10, yPos, colWidth - 20, rowHeight, Qt::AlignCenter, "参考范围");

//     // 绘制表格分隔线
//     painter.drawLine(margin + colWidth, yPos, margin + colWidth, yPos + tableHeight);
//     painter.drawLine(margin + 2*colWidth, yPos, margin + 2*colWidth, yPos + tableHeight);
//     painter.drawLine(margin, yPos + rowHeight, margin + 3*colWidth, yPos + rowHeight);

//     // 填充结果数据
//     QFont normalFont = painter.font();
//     normalFont.setPointSize(12);
//     painter.setFont(normalFont);

//     int row = 1;

//     // 定义参考范围
//     QMap<QString, QString> referenceRanges;
//     referenceRanges["抑郁障碍风险"] = "< 30%";
//     referenceRanges["焦虑障碍风险"] = "< 25%";
//     referenceRanges["睡眠障碍风险"] = "< 20%";
//     referenceRanges["压力水平"] = "< 40%";
//     referenceRanges["注意力水平"] = "> 70%";
//     referenceRanges["认知功能"] = "> 75%";

//     // 定义颜色区间
//     QMap<QString, QPair<double, bool>> thresholds;
//     thresholds["抑郁障碍风险"] = qMakePair(30.0, false);
//     thresholds["焦虑障碍风险"] = qMakePair(25.0, false);
//     thresholds["睡眠障碍风险"] = qMakePair(20.0, false);
//     thresholds["压力水平"] = qMakePair(40.0, false);
//     thresholds["注意力水平"] = qMakePair(70.0, true);
//     thresholds["认知功能"] = qMakePair(75.0, true);

//     // 添加图标映射
//     QMap<QString, QString> itemIcons;
//     itemIcons["抑郁障碍风险"] = ":/images/depression_icon.png";
//     itemIcons["焦虑障碍风险"] = ":/images/anxiety_icon.png";
//     itemIcons["睡眠障碍风险"] = ":/images/sleep_icon.png";
//     itemIcons["压力水平"] = ":/images/stress_icon.png";
//     itemIcons["注意力水平"] = ":/images/attention_icon.png";
//     itemIcons["认知功能"] = ":/images/cognitive_icon.png";

//     for (auto it = results.begin(); it != results.end(); ++it) {
//         QString item = it.key();
//         double value = it.value();
//         QString valueStr = QString::number(value, 'f', 1) + "%";
//         QString reference = referenceRanges.value(item, "N/A");

//         // 交替行背景色
//         if (row % 2 == 0) {
//             QRect rowRect(margin, yPos + row*rowHeight, pageWidth - 2*margin, rowHeight);
//             painter.fillRect(rowRect, QColor(235, 235, 245));
//         }

//         // 根据阈值设置颜色
//         if (thresholds.contains(item)) {
//             double threshold = thresholds[item].first;
//             bool higherIsBetter = thresholds[item].second;

//             if ((higherIsBetter && value < threshold) || (!higherIsBetter && value > threshold)) {
//                 painter.setPen(Qt::red);

//                 // 绘制警告图标
//                 QPixmap warningIcon(":/images/warning_icon.png");
//                 if (!warningIcon.isNull()) {
//                     warningIcon = warningIcon.scaled(20, 20, Qt::KeepAspectRatio, Qt::SmoothTransformation);
//                     painter.drawPixmap(margin + colWidth + colWidth/2 - 30, yPos + row*rowHeight + rowHeight/2 - 10, warningIcon);
//                 }
//             }
//             else {
//                 painter.setPen(Qt::darkGreen);

//                 // 绘制正常图标
//                 QPixmap okIcon(":/images/ok_icon.png");
//                 if (!okIcon.isNull()) {
//                     okIcon = okIcon.scaled(20, 20, Qt::KeepAspectRatio, Qt::SmoothTransformation);
//                     painter.drawPixmap(margin + colWidth + colWidth/2 - 30, yPos + row*rowHeight + rowHeight/2 - 10, okIcon);
//                 }
//             }
//         }

//         // 绘制项目图标
//         if (itemIcons.contains(item)) {
//             QPixmap itemIcon(itemIcons[item]);
//             if (!itemIcon.isNull()) {
//                 itemIcon = itemIcon.scaled(24, 24, Qt::KeepAspectRatio, Qt::SmoothTransformation);
//                 painter.drawPixmap(margin + 15, yPos + row*rowHeight + rowHeight/2 - 12, itemIcon);
//                 painter.drawText(margin + 50, yPos + row*rowHeight, colWidth - 60, rowHeight, Qt::AlignLeft | Qt::AlignVCenter, item);
//             } else {
//                 painter.drawText(margin + 15, yPos + row*rowHeight, colWidth - 30, rowHeight, Qt::AlignLeft | Qt::AlignVCenter, item);
//             }
//         } else {
//             painter.drawText(margin + 15, yPos + row*rowHeight, colWidth - 30, rowHeight, Qt::AlignLeft | Qt::AlignVCenter, item);
//         }

//         // 绘制结果值和参考范围
//         painter.drawText(margin + colWidth + 40, yPos + row*rowHeight, colWidth - 80, rowHeight, Qt::AlignCenter, valueStr);
//         painter.drawText(margin + 2*colWidth + 15, yPos + row*rowHeight, colWidth - 30, rowHeight, Qt::AlignCenter, reference);

//         // 绘制行分隔线
//         painter.setPen(Qt::black);
//         if (row < results.size()) {
//             painter.drawLine(margin, yPos + (row+1)*rowHeight, margin + 3*colWidth, yPos + (row+1)*rowHeight);
//         }

//         row++;
//     }

//     yPos += tableHeight + 40;
// }

// void AnalysisWidget::drawDeviceInfo(QPainter &painter, int &yPos) {
//     int margin = 50;
//     int pageWidth = painter.device()->width();
//     int maxHeight = painter.device()->height();

//     // 检查是否需要新页面
//     if (yPos > maxHeight - 200) {
//         painter.save();
//         painter.restore();
//         yPos = 50;
//         drawLogo(painter, yPos);
//     }

//     // 设备介绍文本
//     QString deviceInfo = "本报告使用的是BioMonitor System脑健康检测系统，该系统集成了多模态生理信号采集设备，包括：\n\n"
//                          "1. 脑电图(EEG)设备：\n   采集前额叶脑电波，监测大脑活动状态，评估认知功能和情绪变化。"
//                          "该设备采用便携式三导脑电监测终端，能够精准地记录患者大脑活动的电信号。\n\n"

//                          "2. 心电图(ECG)设备：\n   记录心脏电活动，分析心率变异性，评估自主神经系统功能和压力水平。"
//                          "系统采用ADS1298心电传感器，具有出色的共模抑制比，能有效消除运动伪像和电极半电池电位。\n\n"

//                          "3. 皮肤电(GSR)设备：\n   测量皮肤电导率变化，反映交感神经活动，用于评估情绪反应和压力水平。"
//                          "采用MAX30009皮肤电传感器，为健身、健康和临床应用提供高性能测量能力。\n\n"

//                          "系统采用先进的机器学习算法，对多模态生理信号进行综合分析，提供科学的脑健康评估和干预建议。"
//                          "通过多模态数据融合技术，实现生理指标的实时、高精度采集与分析，提高脑健康检测的精准度。";

//     // 绘制设备信息背景
//     QRectF boundingRect;
//     painter.drawText(QRectF(margin, yPos, pageWidth - 2*margin, 1000),
//                      Qt::TextWordWrap, deviceInfo, &boundingRect);

//     QRect infoRect(margin - 10, yPos - 10, pageWidth - 2*margin + 20, boundingRect.height() + 20);
//     painter.fillRect(infoRect, QColor(240, 240, 250));
//     painter.drawRect(infoRect);

//     // 计算文本需要的高度并检查是否需要分页
//     if (boundingRect.height() > maxHeight - yPos - 100) {
//         // 分段绘制文本
//         QStringList paragraphs = deviceInfo.split("\n\n");
//         int currentY = yPos;
//         int initialY = yPos;

//         for (const QString &paragraph : paragraphs) {
//             QRectF paraRect;
//             painter.drawText(QRectF(margin, currentY, pageWidth - 2*margin, 1000),
//                              Qt::TextWordWrap, paragraph, &paraRect);

//             // 检查是否需要新页面
//             if (currentY + paraRect.height() > maxHeight - 100 && &paragraph != &paragraphs.last()) {
//                 // 绘制当前页面的设备信息背景
//                 QRect partialInfoRect(margin - 10, initialY - 10, pageWidth - 2*margin + 20, currentY - initialY + paraRect.height() + 10);
//                 painter.fillRect(partialInfoRect, QColor(240, 240, 250));
//                 painter.drawRect(partialInfoRect);

//                 painter.save();
//                 painter.restore();
//                 currentY = 50;
//                 initialY = 50;
//                 drawLogo(painter, currentY);
//             } else {
//                 currentY += paraRect.height() + 15;
//             }

//             // 绘制段落
//             painter.drawText(QRectF(margin, currentY - paraRect.height() - 15, pageWidth - 2*margin, paraRect.height()),
//                              Qt::TextWordWrap, paragraph);

//             // 添加设备图标
//             if (paragraph.contains("脑电图(EEG)设备")) {
//                 QPixmap eegDeviceIcon(":/images/eeg_device.png");
//                 if (!eegDeviceIcon.isNull()) {
//                     eegDeviceIcon = eegDeviceIcon.scaled(80, 80, Qt::KeepAspectRatio, Qt::SmoothTransformation);
//                     painter.drawPixmap(pageWidth - margin - 100, currentY - paraRect.height() - 15, eegDeviceIcon);
//                 }
//             } else if (paragraph.contains("心电图(ECG)设备")) {
//                 QPixmap ecgDeviceIcon(":/images/ecg_device.png");
//                 if (!ecgDeviceIcon.isNull()) {
//                     ecgDeviceIcon = ecgDeviceIcon.scaled(80, 80, Qt::KeepAspectRatio, Qt::SmoothTransformation);
//                     painter.drawPixmap(pageWidth - margin - 100, currentY - paraRect.height() - 15, ecgDeviceIcon);
//                 }
//             } else if (paragraph.contains("皮肤电(GSR)设备")) {
//                 QPixmap gsrDeviceIcon(":/images/gsr_device.png");
//                 if (!gsrDeviceIcon.isNull()) {
//                     gsrDeviceIcon = gsrDeviceIcon.scaled(80, 80, Qt::KeepAspectRatio, Qt::SmoothTransformation);
//                     painter.drawPixmap(pageWidth - margin - 100, currentY - paraRect.height() - 15, gsrDeviceIcon);
//                 }
//             }
//         }

//         // 绘制最终页面的设备信息背景
//         QRect finalInfoRect(margin - 10, initialY - 10, pageWidth - 2*margin + 20, currentY - initialY);
//         painter.fillRect(finalInfoRect, QColor(240, 240, 250));
//         painter.drawRect(finalInfoRect);

//         yPos = currentY + 30;
//     } else {
//         // 如果内容适合当前页面，直接绘制
//         painter.drawText(QRectF(margin, yPos, pageWidth - 2*margin, boundingRect.height()),
//                          Qt::TextWordWrap, deviceInfo);
//         yPos += boundingRect.height() + 40;
//     }
// }

// void AnalysisWidget::drawSectionHeader(QPainter &painter, int &yPos, const QString &title) {
//     int margin = 50;
//     int pageWidth = painter.device()->width();
//     int maxHeight = painter.device()->height();

//     // 检查是否需要新页面
//     if (yPos > maxHeight - 100) {
//         painter.save();
//         painter.restore();
//         yPos = 50;
//         drawLogo(painter, yPos);
//     }

//     // 保存当前字体
//     QFont currentFont = painter.font();

//     // 设置标题字体
//     QFont headerFont("Arial", 18, QFont::Bold);
//     painter.setFont(headerFont);

//     // 添加标题背景
//     QRect headerRect(margin, yPos, pageWidth - 2*margin, 50);
//     painter.fillRect(headerRect, QColor(230, 230, 250));

//     // 绘制标题图标
//     QPixmap sectionIcon;
//     if (title == "生理信号波形") {
//         sectionIcon = QPixmap(":/images/waveform_section_icon.png");
//     } else if (title == "算法分析结果") {
//         sectionIcon = QPixmap(":/images/analysis_section_icon.png");
//     } else if (title == "治疗建议") {
//         sectionIcon = QPixmap(":/images/treatment_section_icon.png");
//     } else if (title == "设备介绍") {
//         sectionIcon = QPixmap(":/images/device_section_icon.png");
//     }

//     if (!sectionIcon.isNull()) {
//         sectionIcon = sectionIcon.scaled(30, 30, Qt::KeepAspectRatio, Qt::SmoothTransformation);
//         painter.drawPixmap(margin + 10, yPos + 10, sectionIcon);
//         painter.drawText(margin + 50, yPos, pageWidth - 2*margin - 50, 50, Qt::AlignLeft | Qt::AlignVCenter, title);
//     } else {
//         painter.drawText(margin + 15, yPos, pageWidth - 2*margin - 15, 50, Qt::AlignLeft | Qt::AlignVCenter, title);
//     }

//     // 绘制下划线
//     QPen pen = painter.pen();
//     pen.setWidth(2);
//     painter.setPen(pen);
//     painter.drawLine(margin, yPos + 50, pageWidth - margin, yPos + 50);

//     // 恢复字体和画笔
//     painter.setFont(currentFont);
//     pen.setWidth(1);
//     painter.setPen(pen);

//     yPos += 60;
// }

// void AnalysisWidget::drawTreatmentSuggestions(QPainter &painter, int &yPos) {
//     int margin = 50;
//     int pageWidth = painter.device()->width();
//     int maxHeight = painter.device()->height();

//     // 检查是否需要新页面
//     if (yPos > maxHeight - 200) {
//         painter.save();
//         painter.restore();
//         yPos = 50;
//         drawLogo(painter, yPos);
//     }

//     // 获取治疗建议
//     QStringList suggestions = getTreatmentSuggestions();

//     // 绘制建议列表
//     QFont normalFont = painter.font();
//     normalFont.setPointSize(12);
//     painter.setFont(normalFont);

//     // 增加行间距和缩进
//     int bulletIndent = 30;
//     int textIndent = 40;
//     int itemSpacing = 30;

//     // 添加建议背景框
//     QRect suggestionsRect(margin - 10, yPos - 10, pageWidth - 2*margin + 20, 10);
//     int initialYPos = yPos;

//     for (int i = 0; i < suggestions.size(); ++i) {
//         QString suggestion = suggestions[i];

//         // 计算文本需要的高度
//         QRectF boundingRect;
//         painter.drawText(QRectF(margin + textIndent, yPos, pageWidth - 2*margin - textIndent, 1000),
//                          Qt::TextWordWrap, suggestion, &boundingRect);

//         // 检查是否需要新页面
//         if (yPos + boundingRect.height() > maxHeight - 100) {
//             // 绘制当前页面的建议背景
//             suggestionsRect.setHeight(yPos - initialYPos);
//             painter.fillRect(suggestionsRect, QColor(240, 250, 240));
//             painter.drawRect(suggestionsRect);

//             painter.save();
//             painter.restore();
//             yPos = 50;
//             drawLogo(painter, yPos);
//             initialYPos = yPos;
//         }

//         // 绘制项目符号
//         QPixmap bulletIcon(":/images/suggestion_bullet.png");
//         if (!bulletIcon.isNull()) {
//             bulletIcon = bulletIcon.scaled(24, 24, Qt::KeepAspectRatio, Qt::SmoothTransformation);
//             painter.drawPixmap(margin, yPos + boundingRect.height()/2 - 12, bulletIcon);
//         } else {
//             QFont bulletFont = painter.font();
//             bulletFont.setPointSize(bulletFont.pointSize() + 4);
//             painter.setFont(bulletFont);
//             painter.drawText(margin, yPos, bulletIndent, boundingRect.height(), Qt::AlignTop, "•");
//             painter.setFont(normalFont);
//         }

//         // 绘制建议文本
//         painter.drawText(margin + textIndent, yPos, pageWidth - 2*margin - textIndent, boundingRect.height(),
//                          Qt::TextWordWrap, suggestion);

//         yPos += boundingRect.height() + itemSpacing;
//     }

//     // 绘制建议背景框（最终高度）
//     suggestionsRect.setHeight(yPos - initialYPos - itemSpacing);
//     painter.fillRect(suggestionsRect, QColor(240, 250, 240));
//     painter.drawRect(suggestionsRect);

//     yPos += 20;
// }

QMap<QString, QString> AnalysisWidget::getSubjectInfo() {
    QMap<QString, QString> info;

    // 默认值
    info["name"] = "未知";
    info["gender"] = "未知";
    info["age"] = "0";
    info["time"] = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss");
    info["id"] = "N/A";
    info["location"] = "未知";
    info["doctor"] = "未知";
    info["note"] = "";

    // 尝试从数据库获取当前被试信息
    QSqlDatabase db = QSqlDatabase::database();
    if (db.isValid() && db.isOpen()) {
        QSqlQuery query;

        // 获取当前被试ID
        query.exec("PRAGMA table_info(subjects)");
        bool hasCurrentSubjectId = false;

        while (query.next()) {
            if (query.value(1).toString() == "current_subject_id") {
                hasCurrentSubjectId = true;
                break;
            }
        }

        int currentSubjectId = 0;
        if (hasCurrentSubjectId) {
            query.exec("SELECT current_subject_id FROM settings WHERE id = 1");
            if (query.next()) {
                currentSubjectId = query.value(0).toInt();
            }
        } else {
            // 尝试从最新记录获取
            query.exec("SELECT id FROM subjects ORDER BY id DESC LIMIT 1");
            if (query.next()) {
                currentSubjectId = query.value(0).toInt();
            }
        }

        // 如果找到有效的被试ID，获取详细信息
        if (currentSubjectId > 0) {
            query.prepare("SELECT name, gender, age, timestamp FROM subjects WHERE id = ?");
            query.addBindValue(currentSubjectId);

            if (query.exec() && query.next()) {
                info["name"] = query.value(0).toString();
                info["gender"] = query.value(1).toString();
                info["age"] = query.value(2).toString();

                // 格式化时间戳
                qint64 timestamp = query.value(3).toLongLong();
                QDateTime dateTime = QDateTime::fromSecsSinceEpoch(timestamp);
                info["time"] = dateTime.toString("yyyy-MM-dd HH:mm:ss");

                // 设置ID
                info["id"] = QString::number(currentSubjectId);

                // 尝试获取可选信息
                QSqlQuery optionalQuery;
                optionalQuery.prepare("SELECT category, field_name, field_value FROM subject_optional_data WHERE subject_id = ?");
                optionalQuery.addBindValue(currentSubjectId);

                if (optionalQuery.exec()) {
                    while (optionalQuery.next()) {
                        QString category = optionalQuery.value(0).toString();
                        QString fieldName = optionalQuery.value(1).toString();
                        QString fieldValue = optionalQuery.value(2).toString();

                        if (category == "location" && fieldName == "name") {
                            info["location"] = fieldValue;
                        } else if (category == "doctor" && fieldName == "name") {
                            info["doctor"] = fieldValue;
                        } else if (category == "note" && fieldName == "content") {
                            info["note"] = fieldValue;
                        }
                    }
                }
            }
        }
    }

    return info;
}

QMap<QString, double> AnalysisWidget::getAnalysisResults() {
    QMap<QString, double> results;

    // 默认值
    results["抑郁障碍风险"] = 15.5;
    results["焦虑障碍风险"] = 12.3;
    results["睡眠障碍风险"] = 18.7;
    results["压力水平"] = 35.2;
    results["注意力水平"] = 78.6;
    results["认知功能"] = 82.1;

    // 尝试从数据库获取分析结果
    QSqlDatabase db = QSqlDatabase::database();
    if (db.isValid() && db.isOpen()) {
        QSqlQuery query;

        // 获取当前被试ID的最新分析结果
        int currentSubjectId = 0;

        // 尝试获取当前被试ID
        query.exec("PRAGMA table_info(settings)");
        bool hasSettingsTable = false;

        while (query.next()) {
            hasSettingsTable = true;
            break;
        }

        if (hasSettingsTable) {
            query.exec("SELECT current_subject_id FROM settings WHERE id = 1");
            if (query.next()) {
                currentSubjectId = query.value(0).toInt();
            }
        }

        if (currentSubjectId == 0) {
            // 尝试从最新记录获取
            query.exec("SELECT id FROM subjects ORDER BY id DESC LIMIT 1");
            if (query.next()) {
                currentSubjectId = query.value(0).toInt();
            }
        }

        // 检查是否存在分析结果表
        query.exec("SELECT name FROM sqlite_master WHERE type='table' AND name='analysis_results'");
        bool hasAnalysisTable = query.next();

        if (hasAnalysisTable && currentSubjectId > 0) {
            // 查询最新的分析结果
            query.prepare("SELECT item_name, value FROM analysis_results "
                          "WHERE subject_id = ? ORDER BY timestamp DESC");
            query.addBindValue(currentSubjectId);

            if (query.exec()) {
                while (query.next()) {
                    QString itemName = query.value(0).toString();
                    double value = query.value(1).toDouble();

                    if (results.contains(itemName)) {
                        results[itemName] = value;
                    }
                }
            }
        }
    }

    return results;
}

QStringList AnalysisWidget::getTreatmentSuggestions() {
    QStringList suggestions;

    // 默认建议
    suggestions << "建议每天进行15-30分钟的冥想练习，帮助减轻压力和焦虑，提高注意力集中。";
    suggestions << "保持规律的睡眠习惯，每晚睡眠7-8小时，睡前避免使用电子设备。";
    suggestions << "每周进行至少150分钟的中等强度有氧运动，如快走、游泳或骑自行车。";
    suggestions << "保持均衡饮食，增加富含omega-3脂肪酸的食物摄入，如深海鱼、亚麻籽等。";
    suggestions << "建立社交支持网络，定期与亲友交流，分享情感和经历。";
    suggestions << "学习压力管理技巧，如深呼吸、渐进性肌肉放松等方法应对日常压力。";

    // 尝试从数据库获取智能干预建议
    QSqlDatabase db = QSqlDatabase::database();
    if (db.isValid() && db.isOpen()) {
        QSqlQuery query;

        // 检查是否存在干预建议表
        query.exec("SELECT name FROM sqlite_master WHERE type='table' AND name='intervention_suggestions'");
        bool hasInterventionTable = query.next();

        if (hasInterventionTable) {
            // 获取当前被试ID
            int currentSubjectId = 0;

            query.exec("SELECT current_subject_id FROM settings WHERE id = 1");
            if (query.next()) {
                currentSubjectId = query.value(0).toInt();
            } else {
                // 尝试从最新记录获取
                query.exec("SELECT id FROM subjects ORDER BY id DESC LIMIT 1");
                if (query.next()) {
                    currentSubjectId = query.value(0).toInt();
                }
            }

            if (currentSubjectId > 0) {
                // 查询最新的干预建议
                query.prepare("SELECT suggestion FROM intervention_suggestions "
                              "WHERE subject_id = ? ORDER BY timestamp DESC LIMIT 10");
                query.addBindValue(currentSubjectId);

                QStringList dbSuggestions;
                if (query.exec()) {
                    while (query.next()) {
                        dbSuggestions << query.value(0).toString();
                    }
                }

                // 如果从数据库获取到建议，则替换默认建议
                if (!dbSuggestions.isEmpty()) {
                    suggestions = dbSuggestions;
                }
            }
        }

        // 如果没有找到干预建议表，尝试从聊天记录中提取建议
        if (!hasInterventionTable) {
            query.exec("SELECT name FROM sqlite_master WHERE type='table' AND name='events'");
            bool hasEventsTable = query.next();

            if (hasEventsTable) {
                // 查询最近的聊天记录中包含"建议"的内容
                query.exec("SELECT detail FROM events WHERE type='chat' AND role='assistant' "
                           "AND detail LIKE '%建议%' ORDER BY timestamp DESC LIMIT 5");

                QStringList chatSuggestions;
                while (query.next()) {
                    QString chatText = query.value(0).toString();

                    // 使用 QString::split 并正确指定 Qt::SkipEmptyParts
                    QStringList sentences = chatText.split(QChar('.'), Qt::SkipEmptyParts);
                    QStringList moreSentences = chatText.split(QChar(0x3002), Qt::SkipEmptyParts);
                    QStringList exclamationSentences = chatText.split(QChar('!'), Qt::SkipEmptyParts);
                    QStringList moreExclamationSentences = chatText.split(QChar(0xFF01), Qt::SkipEmptyParts);
                    QStringList questionSentences = chatText.split(QChar('?'), Qt::SkipEmptyParts);
                    QStringList moreQuestionSentences = chatText.split(QChar(0xFF1F), Qt::SkipEmptyParts);

                    // 合并所有分割结果
                    sentences.append(moreSentences);
                    sentences.append(exclamationSentences);
                    sentences.append(moreExclamationSentences);
                    sentences.append(questionSentences);
                    sentences.append(moreQuestionSentences);

                    for (const QString &sentence : sentences) {
                        if (sentence.contains("建议")) {
                            chatSuggestions << sentence.trimmed() + "。";
                        }
                    }
                }

                // 如果从聊天记录中提取到建议，则添加到建议列表中
                if (!chatSuggestions.isEmpty()) {
                    suggestions.clear();
                    suggestions << "基于您的情况，智能对话系统提供以下建议：";
                    suggestions.append(chatSuggestions);
                }
            }
        }
    }

    return suggestions;
}

// 辅助函数实现
void AnalysisWidget::initUI()
{
    // 创建主布局
    QVBoxLayout* mainLayout = new QVBoxLayout(this);

    // 创建数据选择组
    QGroupBox* dataGroupBox = new QGroupBox(tr("数据选择"), this);
    QFormLayout* dataLayout = new QFormLayout(dataGroupBox);

    // 模型选择
    QHBoxLayout* modelLayout = new QHBoxLayout();
    m_modelEdit = new QLineEdit(this);
    m_modelEdit->setReadOnly(true);
    QPushButton* modelButton = new QPushButton(tr("选择模型"), this);
    modelLayout->addWidget(m_modelEdit);
    modelLayout->addWidget(modelButton);
    dataLayout->addRow(tr("模型:"), modelLayout);

    // 数据集选择
    m_eegDatasetCombo = new QComboBox(this);
    m_ecgDatasetCombo = new QComboBox(this);
    m_gsrDatasetCombo = new QComboBox(this);

    // 加载可用数据集
    loadAvailableDatasets();

    dataLayout->addRow(tr("EEG数据集:"), m_eegDatasetCombo);
    dataLayout->addRow(tr("ECG数据集:"), m_ecgDatasetCombo);
    dataLayout->addRow(tr("GSR数据集:"), m_gsrDatasetCombo);

    // 创建分析参数组
    QGroupBox* paramGroupBox = new QGroupBox(tr("分析参数"), this);
    m_paramLayout = new QStackedLayout(paramGroupBox);

    // 创建各种分析方法的参数界面
    createFFTParamUI();
    createWaveletParamUI();
    createMLParamUI();
    createDLParamUI();

    // 创建输出选项组
    QGroupBox* outputGroupBox = new QGroupBox(tr("输出选项"), this);
    QFormLayout* outputLayout = new QFormLayout(outputGroupBox);

    m_saveResultsCheck = new QCheckBox(tr("保存结果"), this);
    m_saveResultsCheck->setChecked(true);

    m_outputFormatCombo = new QComboBox(this);
    m_outputFormatCombo->addItem("CSV");
    m_outputFormatCombo->addItem("JSON");
    m_outputFormatCombo->addItem("Excel");

    m_generateReportCheck = new QCheckBox(tr("生成报告"), this);
    m_generateReportCheck->setChecked(true);

    outputLayout->addRow("", m_saveResultsCheck);
    outputLayout->addRow(tr("输出格式:"), m_outputFormatCombo);
    outputLayout->addRow("", m_generateReportCheck);

    // 创建操作按钮
    QHBoxLayout* buttonLayout = new QHBoxLayout();
    m_trainButton = new QPushButton(tr("开始训练"), this);
    m_inferenceButton = new QPushButton(tr("开始推理"), this);
    buttonLayout->addWidget(m_trainButton);
    buttonLayout->addWidget(m_inferenceButton);

    // 创建输出显示区域
    m_outputEdit = new QTextEdit(this);
    m_outputEdit->setReadOnly(true);

    // 添加所有组件到主布局
    mainLayout->addWidget(dataGroupBox);
    mainLayout->addWidget(paramGroupBox);
    mainLayout->addWidget(outputGroupBox);
    mainLayout->addLayout(buttonLayout);
    mainLayout->addWidget(m_outputEdit);

    // 连接信号和槽
    connect(modelButton, &QPushButton::clicked, this, &AnalysisWidget::onSelectModel);
    connect(m_eegDatasetCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &AnalysisWidget::onSelectEEGDataset);
    connect(m_ecgDatasetCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &AnalysisWidget::onSelectECGDataset);
    connect(m_gsrDatasetCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &AnalysisWidget::onSelectGSRDataset);
    connect(m_trainButton, &QPushButton::clicked, this, &AnalysisWidget::onStartTraining);
    connect(m_inferenceButton, &QPushButton::clicked, this, &AnalysisWidget::onStartInference);

    // 初始化进程
    m_process = new QProcess(this);
    connect(m_process, &QProcess::readyReadStandardOutput, this, &AnalysisWidget::onProcessOutput);
    connect(m_process, &QProcess::readyReadStandardError, this, &AnalysisWidget::onProcessOutput);
    connect(m_process, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished),
            this, &AnalysisWidget::onProcessFinished);
}

void AnalysisWidget::initConnections()
{
    // 这里可以添加额外的信号-槽连接
}

void AnalysisWidget::loadAvailableDatasets()
{
    // 加载可用的数据集到下拉框
    // 这里仅添加示例数据，实际应用中应从文件系统或数据库加载

    // EEG数据集
    m_eegDatasetCombo->addItem(tr("DEAP情绪数据集"), "DEAP");
    m_eegDatasetCombo->addItem(tr("SEED情绪数据集"), "SEED");
    m_eegDatasetCombo->addItem(tr("BCI竞赛IV数据集"), "BCI_IV");
    m_eegDatasetCombo->addItem(tr("自定义EEG数据集"), "CUSTOM_EEG");

    // ECG数据集
    m_ecgDatasetCombo->addItem(tr("MIT-BIH心律失常数据库"), "MIT-BIH");
    m_ecgDatasetCombo->addItem(tr("PTB诊断ECG数据库"), "PTB");
    m_ecgDatasetCombo->addItem(tr("自定义ECG数据集"), "CUSTOM_ECG");

    // GSR数据集
    m_gsrDatasetCombo->addItem(tr("WESAD压力与情感数据集"), "WESAD");
    m_gsrDatasetCombo->addItem(tr("AMIGOS情感数据集"), "AMIGOS");
    m_gsrDatasetCombo->addItem(tr("自定义GSR数据集"), "CUSTOM_GSR");
}

void AnalysisWidget::createFFTParamUI()
{
    QWidget* fftWidget = new QWidget(this);
    QFormLayout* layout = new QFormLayout(fftWidget);

    // FFT窗口大小
    QSpinBox* windowSizeBox = new QSpinBox(this);
    windowSizeBox->setRange(128, 4096);
    windowSizeBox->setValue(1024);
    windowSizeBox->setSingleStep(128);
    layout->addRow(tr("窗口大小:"), windowSizeBox);

    // FFT窗口类型
    QComboBox* windowTypeCombo = new QComboBox(this);
    windowTypeCombo->addItem("Hamming");
    windowTypeCombo->addItem("Hanning");
    windowTypeCombo->addItem("Blackman");
    windowTypeCombo->addItem("Rectangular");
    layout->addRow(tr("窗口类型:"), windowTypeCombo);

    // FFT重叠率
    QSpinBox* overlapBox = new QSpinBox(this);
    overlapBox->setRange(0, 75);
    overlapBox->setValue(50);
    overlapBox->setSingleStep(5);
    overlapBox->setSuffix("%");
    layout->addRow(tr("重叠率:"), overlapBox);

    // 添加到堆叠布局
    m_paramLayout->addWidget(fftWidget);
}

void AnalysisWidget::createWaveletParamUI()
{
    QWidget* waveletWidget = new QWidget(this);
    QFormLayout* layout = new QFormLayout(waveletWidget);

    // 小波类型
    QComboBox* waveletTypeCombo = new QComboBox(this);
    waveletTypeCombo->addItem("Daubechies");
    waveletTypeCombo->addItem("Haar");
    waveletTypeCombo->addItem("Coiflet");
    waveletTypeCombo->addItem("Symlet");
    layout->addRow(tr("小波类型:"), waveletTypeCombo);

    // 分解层数
    QSpinBox* levelBox = new QSpinBox(this);
    levelBox->setRange(1, 10);
    levelBox->setValue(5);
    layout->addRow(tr("分解层数:"), levelBox);

    // 添加到堆叠布局
    m_paramLayout->addWidget(waveletWidget);
}

void AnalysisWidget::createMLParamUI()
{
    QWidget* mlWidget = new QWidget(this);
    QFormLayout* layout = new QFormLayout(mlWidget);

    // 算法选择
    QComboBox* algorithmCombo = new QComboBox(this);
    algorithmCombo->addItem("SVM");
    algorithmCombo->addItem("Random Forest");
    algorithmCombo->addItem("KNN");
    algorithmCombo->addItem("Gradient Boosting");
    layout->addRow(tr("算法:"), algorithmCombo);

    // 特征选择
    QComboBox* featureSelectionCombo = new QComboBox(this);
    featureSelectionCombo->addItem("PCA");
    featureSelectionCombo->addItem("LDA");
    featureSelectionCombo->addItem("Recursive Feature Elimination");
    featureSelectionCombo->addItem("None");
    layout->addRow(tr("特征选择:"), featureSelectionCombo);

    // 交叉验证折数
    QSpinBox* cvBox = new QSpinBox(this);
    cvBox->setRange(2, 10);
    cvBox->setValue(5);
    layout->addRow(tr("交叉验证折数:"), cvBox);

    // 添加到堆叠布局
    m_paramLayout->addWidget(mlWidget);
}

void AnalysisWidget::createDLParamUI()
{
    QWidget* dlWidget = new QWidget(this);
    QFormLayout* layout = new QFormLayout(dlWidget);

    // 网络架构
    QComboBox* architectureCombo = new QComboBox(this);
    architectureCombo->addItem("CNN");
    architectureCombo->addItem("LSTM");
    architectureCombo->addItem("GRU");
    architectureCombo->addItem("Transformer");
    layout->addRow(tr("网络架构:"), architectureCombo);

    // 训练轮数
    QSpinBox* epochsBox = new QSpinBox(this);
    epochsBox->setRange(1, 1000);
    epochsBox->setValue(100);
    layout->addRow(tr("训练轮数:"), epochsBox);

    // 批量大小
    QSpinBox* batchSizeBox = new QSpinBox(this);
    batchSizeBox->setRange(1, 256);
    batchSizeBox->setValue(32);
    layout->addRow(tr("批量大小:"), batchSizeBox);

    // 学习率
    QDoubleSpinBox* learningRateBox = new QDoubleSpinBox(this);
    learningRateBox->setRange(0.00001, 0.1);
    learningRateBox->setValue(0.001);
    learningRateBox->setDecimals(5);
    learningRateBox->setSingleStep(0.0001);
    layout->addRow(tr("学习率:"), learningRateBox);

    // 添加到堆叠布局
    m_paramLayout->addWidget(dlWidget);
}

void AnalysisWidget::updateUIForAnalysisMethod()
{
    // 根据分析方法切换参数界面
    if (m_analysisMethod == "FFT") {
        m_paramLayout->setCurrentIndex(0);
    } else if (m_analysisMethod == "Wavelet") {
        m_paramLayout->setCurrentIndex(1);
    } else if (m_analysisMethod == "ML") {
        m_paramLayout->setCurrentIndex(2);
    } else if (m_analysisMethod == "DL") {
        m_paramLayout->setCurrentIndex(3);
    }
}

void AnalysisWidget::setControlsEnabled(bool enabled)
{
    // 启用或禁用界面控件
    m_eegDatasetCombo->setEnabled(enabled);
    m_ecgDatasetCombo->setEnabled(enabled);
    m_gsrDatasetCombo->setEnabled(enabled);
    m_trainButton->setEnabled(enabled);
    m_inferenceButton->setEnabled(enabled);
    m_saveResultsCheck->setEnabled(enabled);
    m_outputFormatCombo->setEnabled(enabled);
    m_generateReportCheck->setEnabled(enabled);

    // 禁用所有参数界面中的控件
    for (int i = 0; i < m_paramLayout->count(); ++i) {
        QWidget* widget = m_paramLayout->widget(i);
        if (widget) {
            for (QObject* child : widget->children()) {
                QWidget* childWidget = qobject_cast<QWidget*>(child);
                if (childWidget) {
                    childWidget->setEnabled(enabled);
                }
            }
        }
    }
}

QMap<QString, QVector<QPair<qint64, double>>> AnalysisWidget::getWaveformDataFromDB() {
    QMap<QString, QVector<QPair<qint64, double>>> waveformData;

    // 初始化空的数据向量
    waveformData["EEG"] = QVector<QPair<qint64, double>>();
    waveformData["ECG"] = QVector<QPair<qint64, double>>();
    waveformData["GSR"] = QVector<QPair<qint64, double>>();

    // 获取正确的数据库连接
    QSqlDatabase db = getDatabase();
    if (!db.isValid() || !db.isOpen()) {
        qWarning() << "无法获取数据库连接";
        return waveformData;
    }

    // 获取当前被试ID
    int currentSubjectId = getCurrentSubjectId();
    //int currentSubjectId = 1;
    if (currentSubjectId <= 0) {
        qWarning() << "无法确定当前被试ID";
        return waveformData;
    }

    // 获取最近的EEG数据（最多500个点）
    QSqlQuery eegQuery(db);
    eegQuery.prepare("SELECT timestamp, fp1, fpz, fp2 FROM eeg_data WHERE subject_id = ? ORDER BY timestamp DESC LIMIT 500");
    eegQuery.addBindValue(currentSubjectId);

    if (eegQuery.exec()) {
        QVector<QPair<qint64, double>> eegData;
        while (eegQuery.next()) {
            qint64 timestamp = eegQuery.value(0).toLongLong();
            // 使用fp1通道作为示例
            double value = eegQuery.value(1).toDouble();
            eegData.prepend(qMakePair(timestamp, value));
        }
        waveformData["EEG"] = eegData;
    } else {
        qWarning() << "EEG数据查询失败:" << eegQuery.lastError().text();
    }

    // 获取最近的ECG数据（最多500个点）
    QSqlQuery ecgQuery(db);
    ecgQuery.prepare("SELECT timestamp, ch1 FROM ecg_data WHERE subject_id = ? ORDER BY timestamp DESC LIMIT 500");
    ecgQuery.addBindValue(currentSubjectId);

    if (ecgQuery.exec()) {
        QVector<QPair<qint64, double>> ecgData;
        while (ecgQuery.next()) {
            qint64 timestamp = ecgQuery.value(0).toLongLong();
            double value = ecgQuery.value(1).toDouble();
            ecgData.prepend(qMakePair(timestamp, value));
        }
        waveformData["ECG"] = ecgData;
    } else {
        qWarning() << "ECG数据查询失败:" << ecgQuery.lastError().text();
    }

    // 获取最近的GSR数据（最多500个点）
    QSqlQuery gsrQuery(db);
    gsrQuery.prepare("SELECT timestamp, value1 FROM gsr_data WHERE subject_id = ? ORDER BY timestamp DESC LIMIT 500");
    gsrQuery.addBindValue(currentSubjectId);

    if (gsrQuery.exec()) {
        QVector<QPair<qint64, double>> gsrData;
        while (gsrQuery.next()) {
            qint64 timestamp = gsrQuery.value(0).toLongLong();
            double value = gsrQuery.value(1).toDouble();
            gsrData.prepend(qMakePair(timestamp, value));
        }
        waveformData["GSR"] = gsrData;
    } else {
        qWarning() << "GSR数据查询失败:" << gsrQuery.lastError().text();
    }

    return waveformData;
}
